package com.zhihuichongcheng.application.ui.main.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.domain.EaseUser;
import com.smartlib.cmnObject.ui.NoScrollViewPager;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.yunkeshuzhi.common.utils.JsonUtils;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.task.TaskBean;
import com.zhihuichongcheng.application.bean.task.TaskPriority;
import com.zhihuichongcheng.application.bean.task.TaskType;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.net.HttpManager;
import com.zhihuichongcheng.application.ui.main.adapter.MainAdapter;
import com.zhihuichongcheng.application.ui.main.fragment.ApprovalCopyFragment;
import com.zhihuichongcheng.application.ui.main.fragment.CircleFragment;
import com.zhihuichongcheng.application.ui.main.fragment.CoordinationFragment;
import com.zhihuichongcheng.application.ui.main.fragment.ImFragment;
import com.zhihuichongcheng.application.ui.main.fragment.OpenClassFragment;
import com.zhihuichongcheng.application.util.DialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static final String ACTION_FROM_THREE_WATER = "action_invitation_from_group";//三水的action

    private NoScrollViewPager mNoScrollViewPager;
    private MainAdapter mMainAdapter;
    private List<Fragment> mFragments = new ArrayList<>();
    private ImFragment mImFragment;
    private Broad mBroad;
    private View mImBottom;
    private CircleFragment mCircleFragment;
    private OpenClassFragment mOpenClassFragment;
    private CoordinationFragment mCoordinationFragment;
    private ApprovalCopyFragment mApprovalFragment;
    private LinearLayout mLlMessage, mLlCoordination, mLlOpneclass, mLlCricle;
    private TextView mTvMessage, mTvApproval, mTvCoordination, mTvOpenClass, mTvCricle;
    private ImageView mImMessage, mImApproval, mImCoordination, mImOpneclass, mImCricle;
    private TextView mTvWaitCount;
    private RelativeLayout mRlApproval;
    private int mIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        mBroad = new Broad();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_FROM_THREE_WATER);
        registerReceiver(mBroad, filter);
        isStartAnimation = false;
    }

    private void initView() {
        mTvWaitCount = (TextView) findViewById(R.id.tv_waitCount);
        mImBottom = findViewById(R.id.im_bottom);
        mNoScrollViewPager = (NoScrollViewPager) findViewById(R.id.vp_main);
        mNoScrollViewPager.setNoScroll(true);
        mTvMessage = (TextView) findViewById(R.id.tv_message);
        mLlMessage = (LinearLayout) findViewById(R.id.ll_message);
        mImMessage = (ImageView) findViewById(R.id.im_message);

        mTvApproval = (TextView) findViewById(R.id.tv_Approval);
        mRlApproval = (RelativeLayout) findViewById(R.id.ll_approval);
        mImApproval = (ImageView) findViewById(R.id.im_approval);

        mTvCoordination = (TextView) findViewById(R.id.tv_coordination);
        mLlCoordination = (LinearLayout) findViewById(R.id.ll_coordination);
        mImCoordination = (ImageView) findViewById(R.id.im_coordination);

        mTvOpenClass = (TextView) findViewById(R.id.tv_open_class);
        mLlOpneclass = (LinearLayout) findViewById(R.id.ll_openclass);
        mImOpneclass = (ImageView) findViewById(R.id.im_openclass);

        mTvCricle = (TextView) findViewById(R.id.tv_cricle);
        mLlCricle = (LinearLayout) findViewById(R.id.ll_cricle);
        mImCricle = (ImageView) findViewById(R.id.im_cricle);

        mLlMessage.setOnClickListener(this);
        mRlApproval.setOnClickListener(this);
        mLlCoordination.setOnClickListener(this);
        mLlOpneclass.setOnClickListener(this);
        mLlCricle.setOnClickListener(this);
        clear();
        mTvMessage.setTextColor(getResources().getColor(R.color.btn_blue_normal));
        mImMessage.setBackgroundResource(R.drawable.ic_tab_message_selected);
    }

    private void initData() {

        mImFragment = new ImFragment();

        mCircleFragment = new CircleFragment();
        mOpenClassFragment = new OpenClassFragment();
        mCoordinationFragment = new CoordinationFragment();
        mApprovalFragment = new ApprovalCopyFragment();
        mFragments.add(mImFragment);
        mFragments.add(mApprovalFragment);
        mFragments.add(mCoordinationFragment);
        mFragments.add(mOpenClassFragment);
        mFragments.add(mCircleFragment);
        mImFragment.setConversationListItemClickListener(new ImFragment.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation) {

            }
        });
        mMainAdapter = new MainAdapter(getSupportFragmentManager(), mFragments);
        mNoScrollViewPager.setAdapter(mMainAdapter);
        final Map<String, EaseUser> contactsMap = new HashMap<>();
        Intent intent = getIntent();
        if (intent != null) {
            mIndex = intent.getIntExtra("index", -1);
        }
        if (mIndex > 0) {
            mNoScrollViewPager.setCurrentItem(mIndex, false);
            clear();
            mTvApproval.setTextColor(getResources().getColor(R.color.activity_color));
            mImApproval.setImageResource(R.drawable.ic_tab_approval_selected);
        }

        requestTaskPriority();
        requestTaskType();
    }

    private void clear() {
        mTvMessage.setTextColor(getResources().getColor(R.color.color_7F8389));
        mImMessage.setBackgroundResource(R.drawable.ic_tab_message_normal);
        mTvApproval.setTextColor(getResources().getColor(R.color.color_7F8389));
        mImApproval.setImageResource(R.drawable.ic_tab_approval_normal);
        mTvCoordination.setTextColor(getResources().getColor(R.color.color_7F8389));
        mImCoordination.setBackgroundResource(R.drawable.ic_tab_coordination_normal);
        mTvOpenClass.setTextColor(getResources().getColor(R.color.color_7F8389));
        mImOpneclass.setBackgroundResource(R.drawable.ic_tab_openclass_normal);
        mTvCricle.setTextColor(getResources().getColor(R.color.color_7F8389));
        mImCricle.setBackgroundResource(R.drawable.ic_tab_cricle_normal);
    }

    /**
     * 请求任务优先级列表
     */
    private void requestTaskPriority() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        HttpManager.getInstance(getContext()).post(NetworkAPI.MISSION_PRIORITY, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskPriority> priorityList = GsonUtil.paraeFromStringToList(value, TaskPriority.class);
                TaskBean.setTaskPriorities(priorityList);
            }

            @Override
            public void onFailure(String value) {
            }
        }, params);
    }

    /**
     * 请求任务类型列表
     */
    private void requestTaskType() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        HttpManager.getInstance(getContext()).post(NetworkAPI.MISSION_TYPE, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskType> taskTypeList = GsonUtil.paraeFromStringToList(value, TaskType.class);
                TaskBean.setTaskTypeList(taskTypeList);
            }

            @Override
            public void onFailure(String value) {
            }
        }, params);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mUser = app.getUser();
        mNoScrollViewPager.setCurrentItem(0, false);
        clear();
        mTvMessage.setTextColor(getResources().getColor(R.color.activity_color));
        mImMessage.setBackgroundResource(R.drawable.ic_tab_message_selected);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroad);
    }

    @Override
    protected void onResume() {
        super.onResume();
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        mManager.post(NetworkAPI.Approval_Wait_count, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                int count = 0;
                try {
                    count = Integer.parseInt(value);
                } catch (Exception e) {
                    count = 0;
                    e.printStackTrace();
                }
                if (count > 0) {
                    spUtil.putInt("waitCount", count);
                    mTvWaitCount.setText((spUtil.getInt("rejectCount") + spUtil.getInt("waitCount")) + "");
                    mTvWaitCount.setVisibility(View.VISIBLE);
                } else {
                    mTvWaitCount.setVisibility(View.GONE);
                }
                if (null != spUtil)
                    spUtil.putInt("waitCount", count);
                if (null != mApprovalFragment)
                    mApprovalFragment.reflush();
            }

            @Override
            public void onFailure(String value) {
                mTvWaitCount.setVisibility(View.GONE);
            }
        }, params);
        mManager.post(NetworkAPI.Approval_Reject_count, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                int count = 0;
                try {
                    count = JsonUtils.getJsonObject(value).get("count").getAsInt();
                } catch (Exception e) {
                    count = 0;
                    e.printStackTrace();
                }
                if (count > 0) {
                    spUtil.putInt("rejectCount", count);
                    mTvWaitCount.setText((spUtil.getInt("rejectCount") + spUtil.getInt("waitCount")) + "");
                    mTvWaitCount.setVisibility(View.VISIBLE);
                } else {
                    mTvWaitCount.setVisibility(View.GONE);
                }
                if (null != spUtil)
                    spUtil.putInt("rejectCount", count);
                if (null != mApprovalFragment)
                    mApprovalFragment.reflush();
            }

            @Override
            public void onFailure(String value) {
                mTvWaitCount.setVisibility(View.GONE);
            }
        }, params);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_message:
                clear();
                mTvMessage.setTextColor(getResources().getColor(R.color.activity_color));
                mImMessage.setBackgroundResource(R.drawable.ic_tab_message_selected);
                mNoScrollViewPager.setCurrentItem(0, false);
                break;
            case R.id.ll_approval:
                clear();
                mTvApproval.setTextColor(getResources().getColor(R.color.activity_color));
                mImApproval.setImageResource(R.drawable.ic_tab_approval_selected);
//                startActivity(MainCricleActivity.class);
                mNoScrollViewPager.setCurrentItem(1, false);
                break;
            case R.id.ll_coordination:
                clear();
                mTvCoordination.setTextColor(getResources().getColor(R.color.activity_color));
                mImCoordination.setBackgroundResource(R.drawable.ic_tab_coordination_selected);
                mNoScrollViewPager.setCurrentItem(2, false);
                break;
            case R.id.ll_openclass:
                clear();
                mTvOpenClass.setTextColor(getResources().getColor(R.color.activity_color));
                mImOpneclass.setBackgroundResource(R.drawable.ic_tab_openclass_selected);
                mNoScrollViewPager.setCurrentItem(3, false);
                break;
            case R.id.ll_cricle:
                clear();
                mTvCricle.setTextColor(getResources().getColor(R.color.activity_color));
                mImCricle.setBackgroundResource(R.drawable.ic_tab_cricle_selected);
                mNoScrollViewPager.setCurrentItem(4, false);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        DialogUtils.showAlertDialog(this, "确定退出?", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                finish();
            }
        });
    }

    class Broad extends BroadcastReceiver {
        public Broad() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (null != intent && !StringUtil.isEmpty(intent.getAction())) {
                String action = intent.getAction();
                if (ACTION_FROM_THREE_WATER.equals(action)) {
                    onGetThreeWaterAction(intent);
                }
            }
        }


        private void onGetThreeWaterAction(Intent intent) {
            int type = -1;
            if (intent != null) {
                if (intent.hasExtra("type")) {
                    type = intent.getIntExtra("type", -1);
                }
            }
            if (type > 0) {
                switch (type) {
                    case 1:
                        spUtil.putBoolean(mContext, "news", true);
                        break;
                    case 2:
                        spUtil.putBoolean(mContext, "notice", true);
                        break;
                    case 3:
                        spUtil.putBoolean(mContext, "mettingNotice", true);
                        break;
                    case 5:
                        int size = spUtil.getInt("waitCount");
                        spUtil.putInt("waitCount", size + 1);
                        break;
                    default:
                        break;
                }
                if (type == 5) {
                    mApprovalFragment.reflush();
                } else {
                    mImFragment.refulsh(type);
                }
            } else {
                mImFragment.refresh();
            }
        }
    }
}
